package com.houdoudou.supplier.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.supplier.R;
import com.houdoudou.supplier.SupplierMainActivity;
import com.houdoudou.supplier.bean.Sort;
import com.houdoudou.supplier.bean.Supplier;
import com.houdoudou.supplier.common.CommonFunction;
import com.houdoudou.supplier.common.Constant;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class IndexAllFragment extends Fragment {
	TextView result;
	View.OnClickListener myOnclickListener;
	Button confirm;
	ProgressBar progres;
	ListView listview_index;
	MyListAdapter myListAdapter;
//	List<Map<String,Object>> list_data_indexes=new ArrayList<Map<String,Object>>();
	JSONArray indexesJA= new JSONArray();

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 View view =inflater.inflate(R.layout.frg_indexall, container, false);
           init_listener();
           init_component(view);
           confirm.performClick();
		 return view;
	}

	private void init_listener(){
		
		
		myOnclickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				    result.setText("请稍后");
				    progres.setVisibility(View.VISIBLE);
					confirm.setEnabled(false);
					String[] params= new String[10];
	   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
	                params[1]="searchIndex"; //PostCode
	              //  params[2]=jsonData.toString();
	                JSONObject indexJO=new JSONObject();
	                indexJO.put(Sort.SUPPLIER, Constant.supplierJO.get(Supplier.TELNUM));
	                params[2]=indexJO.toString();
	                new HttpPostTaskforIndexALL().execute(params);
				  
				
			}
		};		
	}
	
	
	private void init_component(View view){
		
		
		confirm=(Button) view.findViewById(R.id.btn_confirm_frg_indexall);
	
		result=(TextView) view.findViewById(R.id.tv_functionresult_frg_indexall);
		progres= (ProgressBar) view.findViewById(R.id.prgs_frg_indexall);
		listview_index= (ListView) view.findViewById(R.id.listView_frg_indexall);
		//////////////////////
		confirm.setOnClickListener(myOnclickListener);
		progres.setVisibility(View.INVISIBLE);
		
		myListAdapter= new MyListAdapter(getActivity());
		listview_index.setAdapter(myListAdapter);
		
		
	}
	
	
	
	
	
	private  class HttpPostTaskforIndexALL extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			  Map<String,Object> map =	CommonFunction.UniversalHttpPost(params);		             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
			// TODO Auto-generated method stub
		  //	super.onPostExecute(result);
			confirm.setEnabled(true);
			result.setText("");
			 progres.setVisibility(View.INVISIBLE);
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				  result.setText("提示:网络故障或者网络配置有误，无法连接到服务器");
			     return ; 
			}
			 
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				}catch(JSONException e){
					errorInfo="JSON解析错误";
				}
				 result.setText("提示:"+errorInfo);
       						   												      		       
		       if(success){   
		    	   if(json.getString("affair").equals("searchIndex")){
		    	   indexesJA= json.getJSONArray("sorts");
		    	   myListAdapter.notifyDataSetChanged(); }
		    	   
		    	   if(json.getString("affair").equals("deleteIndex")){
		    		int id=   json.getJSONObject("sort").getInt(Sort.ID);
		    		  for(int i= indexesJA.size()-1;i>=0;i--){
		    			  if(id==indexesJA.getJSONObject(i).getInt(Sort.ID)){
		    				  indexesJA.remove(i); 
		    				  myListAdapter.notifyDataSetChanged();
		    				  break;
		    			  }
		    		  }
		    		  
		    	   }//deleteIndex
		    	   
		             } 
		
		} //onPostExecute
 } //AsyncTask
	
	class MyListAdapter extends BaseAdapter {
		   
		    private LayoutInflater layoutInflater;  
		    private Context context;  
		    
		public MyListAdapter(Context context) {
				super();
				this.context = context;
			    this.layoutInflater=LayoutInflater.from(context); 
			}
		
		
		final class Zujian{  
		    public TextView zj_id,zj_name,zj_showno;  
	        public Button delete,modify;
	       
	      
	    
	   }   //end of Zujian

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			 return indexesJA.size(); 
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			 return  indexesJA.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position; 
		}
	 
		@Override
		public View getView(int position, View  convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int selectID = position;   
			 Zujian zujian=null;  
		        if(convertView==null){  
		            zujian=new Zujian();  
		            //获得组件，实例化组件  
		            convertView=layoutInflater.inflate(R.layout.list_indexall, null);  
		          
		            zujian.zj_id=(TextView) convertView.findViewById(R.id.tv_id_list_index_all);
		            zujian.zj_name=(TextView) convertView.findViewById(R.id.tv_name_list_index_all); 
		          
		            zujian.delete=  (Button) convertView.findViewById(R.id.btn_delete_list_index_all);
		            zujian.modify= (Button) convertView.findViewById(R.id.btn_modify_list_index_all);
		            zujian.zj_showno=(TextView) convertView.findViewById(R.id.tv_shownum_list_index_all);       
		            convertView.setTag(zujian);  
		            System.out.println("position----"+position+"------inflated");
		        }else{   System.out.println("position----"+position+"-------not inflated");
		            zujian=(Zujian)convertView.getTag();  
		        }  
		        //绑定数据  
		        zujian.zj_id.setText(""+indexesJA.getJSONObject(selectID).getInt(Sort.ID));
		        zujian.zj_showno.setText(""+indexesJA.getJSONObject(selectID).getInt(Sort.DISPLAY));
		        zujian.zj_name.setText(""+indexesJA.getJSONObject(selectID).getString(Sort.NAME));
		        
		       zujian.delete.setOnClickListener(new View.OnClickListener() {			
				@Override
				public void onClick(View v) {
					String[] params= new String[10];
	   	            params[0]=Constant.BaseUrl+Constant.SupplierUrl;
	                params[1]="deleteIndex"; //PostCode	               
	                params[2]=indexesJA.getJSONObject(selectID).toString();
	                new HttpPostTaskforIndexALL().execute(params);				
				}
			});
		       zujian.modify.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						Message msg = new Message();               
	                    msg.what=2;
	                   msg.arg1=0;
	                   msg.arg2=0;
	                  Bundle bundle= new Bundle(); 
	                  bundle.putString("affair", "updateIndex");
	                  bundle.putString("index", indexesJA.getJSONObject(selectID).toString());
	          	      bundle.putString("tag", "TAG_UPDATEINDEX");
	          		  bundle.putString("title", "修改分类");
	          		
	                  msg.obj=bundle;
	                   SupplierMainActivity.myMainHandler.sendMessage(msg);					
					}
				}); 
		        
		        return convertView;
	           } 
	      }// end Adapter
			 
}
